<template>
  <el-upload
    class="avatar-uploader"
    :action="action"
    :show-file-list="false"
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
  >
    <div v-if="imageUrl">
      <img :src="imageUrl" class="avatar">
    </div>

    <div v-else class="text">
      <i class="el-icon-plus avatar-uploader-icon" />
      <p>{{ title }}</p>
    </div>
  </el-upload>
</template>
<script>
import { getToken } from '@/utils/auth' // get token from cookie
export default {
  name: 'Upload',
  components: {
    
  },
  props: {
    title: String,
    img: String,
    imgType: String,
    prop: String,
    action: {
      type: String,
      default: process.env.VUE_APP_BASE_API + '/common/v1/uploadFile'
    }
  },
  data() {
    return {
      imageUrl: '',
    }
  },
  computed: {
	headers() {
		return{
			"Authorization": getToken() // 直接从本地获取token就行
		}
	}
},
  watch: {
    img: {
      handler(cur) {
        if (cur) {
          this.imageUrl = this.$IMG_URL + cur
        }
      },
      immediate: true
    }
  },
  methods: {
    // 上传成功后的处理
    handleSuccess(res, file) {
      // console.log('imgType',this.imgType)
      // console.log(3123123123, res.result)
      var obj = {}
      obj.url =res.result.url
      obj.imgType =this.imgType
      this.imageUrl = this.$IMG_URL + res.result.url
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.$emit('success', obj)
    },

    // 上传之前的验证
    beforeUpload(file) {
      // 支持上传的格式
      const format = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf']
      const isOk = format.some(item => file.type === item)

      const isLimit = file.size / 1024 / 1024 < 5 // 最大不能超过5M

      if (!isOk) {
        this.$message.error('上传图片格式不正确!')
      }

      if (!isLimit) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isOk && isLimit
    }
  }
}
</script>
<style lang="scss" scoped>
.object {
  display: block;
}
.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .text {
    position: relative;
    p {
      position: absolute;
      top: 110px;
      left: 0;
      width: 100%;
      text-align: center;
      color: #919191;
    }
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: auto;
  height: 178px;
  display: block;
}
</style>
